<?php if (!defined('ITPK')) exit('You can not directly access the file.');

/**
 * 签到插件
 * @author 冬天的秘密
 * @link http://bbs.itpk.cn
 * @version 1.0
 */

class WebsignHandler extends AbstractpluginHandler {

	private $nick_name = "";
	private $mark = "plugin_sign";

	/**
	 * 插件入口方法，所有插件都必须有main方法和继承AbstractpluginHandler类
	 */
	public function main() {
		$msg = $this->msg;
		$uin = $this->robot['uin'];
		$group_member_id = $this->object['id'];
		$sign = $this->getMe($uin, $group_member_id);
		$time = time();
		$year = date("Y", $time);
		$month = date("m", $time);
		$day = date("d", $time);
		$this->nick_name = $this->getNameForMsg();

		if ($sign) {
			$id = $sign['id'];
			$status = $sign['status'];
			$days = $this->getRecordByDate($id, $year, $month);
			$not_days = $this->getNotSignByDays($days, $day);
			$is_permissions = $this->is_permissions();
			if ($status == "addsign") {
				$this->updateStatus($uin, $group_member_id, "");
				$this->updatePluginId();
				$addSignGold = $this->getValueByName($this->mark, "add_sign_gold", 500);
				if ($msg == "全部") {
					if (count($not_days) <= 0) return ReplyUtil::getReply($this->nick_name . "您好，您本月至今未漏签，无需补签");
					$deductGold = $addSignGold * count($not_days);
					if ($deductGold > $this->object['gold']) return ReplyUtil::getReply($this->nick_name . "您好，您的金币不足，无法补签");
				} else {
					$add_days = explode(",", $msg);
					$not_days = $this->getNotSignByNotDays($not_days, $add_days);
					if (count($not_days) <= 0) return ReplyUtil::getReply($this->nick_name . "您好，补签失败，未收取金币");
					$deductGold = $addSignGold * count($not_days);
					if ($deductGold > $this->object['gold']) return ReplyUtil::getReply($this->nick_name . "您好，您的金币不足，无法补签");
				}
				if ($this->addSignRecord($id, $year, $month, implode(",", array_merge($days, $not_days)))) {
					$this->groupmemberPer->updateGold($group_member_id, $deductGold);
					$this->updateSign($uin, $group_member_id, $sign['continuous_sign'], intval($sign['total_sign']) + 1, $sign['last_sign_time']);
					return ReplyUtil::getReply($this->nick_name . "您好，补签成功，共补签" . count($not_days) . "天，收取" . $deductGold . "金币");
				}
				return ReplyUtil::getReply($this->nick_name . "您好，补签失败，未收取金币");
			} elseif ($status == "max_continuous_sign" || $status == "sign_gold" || $status == "sign_experience" || $status == "con_sign_add_gold" || $status == "con_sign_add_experience" || $status == "repeat_gold" || $status == "repeat_experience" || $status == "add_sign_gold") {
				$this->updateStatus($uin, $group_member_id, "");
				$this->updatePluginId();
				if (is_numeric($msg)) {
					return ReplyUtil::getReply($this->replaceSys($this->mark, $status, $msg) ? "设置成功" : "设置失败");
				}
				return ReplyUtil::getReply("设置不合法，请输入正确的数字");
			}

			$now_time = date('Y-m-d', $time);
			$continuous_sign = $sign['continuous_sign'];
			$total_sign = $sign['total_sign'];
			$last_sign_time = $sign['last_sign_time'];
			if ($msg == "签到") {
				if ($now_time != $last_sign_time) {
					$sign_experience = $this->getValueByName($this->mark, "sign_experience", 50);
					$con_sign_add_experience = $this->getValueByName($this->mark, "con_sign_add_experience", 10);
					$sign_gold = $this->getValueByName($this->mark, "sign_gold", 100);
					$con_sign_add_gold = $this->getValueByName($this->mark, "con_sign_add_gold", 20);
					$max_continuous_sign = $this->getValueByName($this->mark, "max_continuous_sign", 7);
					//总签到次数加1
					$total_sign += 1;
					//当前时间-1天跟最后签到时间做对比，如果相等则为连续签到，不相等则把连续签到天数归1
					if (date("Y-m-d", strtotime("-1 day", $time)) == $last_sign_time) {
						$continuous_sign += 1;
						$continuous_sign = $continuous_sign >= $max_continuous_sign ?  $max_continuous_sign : $continuous_sign;
					} else {
						$continuous_sign = 1;
					}
					$experience = $continuous_sign * $con_sign_add_experience + $sign_experience;
					$gold = $continuous_sign * $con_sign_add_gold + $sign_gold;
					$this->groupmemberPer->updateExperience($sign['group_member_id'], $experience, true);
					$this->groupmemberPer->updateGold($sign['group_member_id'], $gold, true);
					$this->updatePluginId();
					$this->updateSign($uin, $group_member_id, $continuous_sign, $total_sign, $now_time);
					array_push($days, $day);
					$this->addSignRecord($sign['id'], date("Y", $time), date("m", $time), implode(",", $days));
					$content = $this->nick_name . "，恭喜您签到成功，获取" . $experience . "经验和" . $gold . "金币";
					return ReplyUtil::getReply($content);
				}
				$repeat_experience = $this->getValueByName($this->mark, "repeat_experience", 10);
				$repeat_gold = $this->getValueByName($this->mark, "repeat_gold", 20);
				$this->groupmemberPer->updateExperience($sign['group_member_id'], $repeat_experience);
				$this->groupmemberPer->updateGold($sign['group_member_id'], $repeat_gold);
				$this->updatePluginId();
				$content = $this->nick_name . "，重复签到，没收" . $repeat_experience . "经验和" . $repeat_gold . "金币";
				return ReplyUtil::getReply($content);
			} elseif ($msg == "补签") {
				$addSignGold = $this->getValueByName($this->mark, "add_sign_gold", 500);
				$this->updateStatus($uin, $group_member_id, "addsign");
				$not_days_str = implode(",", $not_days);
				$content = $this->nick_name . "您好，您本月未签到日期如下：" . CR . $not_days_str . CR . "补签请回复日期，多个用“,”隔开，补签全部请回复“全部”" . CR . "注意：补签一天收取" . $addSignGold . "金币";
				return ReplyUtil::getReply($content);
			} elseif ($msg == "签到记录") {
				$this->updatePluginId();
				$content = FaceUtil::get(114) . $this->nick_name . "您好" . CR;
				$content .= FaceUtil::get(115) . "您今天" . ($now_time != $last_sign_time ? "没有" : "已经") . "签到" . CR;
				$content .= FaceUtil::get(114) . "连续签到：" . $continuous_sign . "天" . CR;
				$content .= FaceUtil::get(115) . "总共签到：" . $total_sign . "天";
				return ReplyUtil::getReply($content);
			}
			if ($this->is_permissions() || $this->is_manager()) {
				if ($msg == "设置最大连签") {
					$this->updateStatus($uin, $group_member_id, "max_continuous_sign");
					return ReplyUtil::getReply("请输入达到最大签到奖励需要连续签到的天数（比如设置为7，则表示连续签到7天和7天以上的奖励一样）：");
				} elseif ($msg == "设置签到金币") {
					$this->updateStatus($uin, $group_member_id, "sign_gold");
					return ReplyUtil::getReply("请输入签到增加的基本金币：");
				} elseif ($msg == "设置签到经验") {
					$this->updateStatus($uin, $group_member_id, "sign_experience");
					return ReplyUtil::getReply("请输入签到增加的基本经验：");
				} elseif ($msg == "设置连签金币") {
					$this->updateStatus($uin, $group_member_id, "con_sign_add_gold");
					return ReplyUtil::getReply("请输入连签奖励的基本金币（连签奖励=连签天数*连签基本金币）：");
				} elseif ($msg == "设置连签经验") {
					$this->updateStatus($uin, $group_member_id, "con_sign_add_experience");
					return ReplyUtil::getReply("请输入连签奖励的基本经验（连签奖励=连签天数*连签基本经验）：");
				} elseif ($msg == "设置重签金币") {
					$this->updateStatus($uin, $group_member_id, "repeat_gold");
					return ReplyUtil::getReply("请输入重复签到扣除的金币：");
				} elseif ($msg == "设置重签经验") {
					$this->updateStatus($uin, $group_member_id, "repeat_experience");
					return ReplyUtil::getReply("请输入重复签到扣除的经验：");
				} elseif ($msg == "设置补签金币") {
					$this->updateStatus($uin, $group_member_id, "add_sign_gold");
					return ReplyUtil::getReply("请输入补签一天收取的金币：");
				}
			} else {
				$this->updatePluginId();
			}
		}
	}

	/**
	 * 根据未某月未签到天数和补签天数获取正确的补签天数
	 * @param array $not_days
	 * @param array $add_days
	 * @return array
	 */
	public function getNotSignByNotDays($not_days, $add_days) {
		$not_sign = array();
		for ($k = 0; $k < count($add_days); $k++) {
			if ($add_days[$k] == "" || !is_numeric($add_days[$k])) continue;
			if (in_array($add_days[$k], $not_days)) array_push($not_sign, $add_days[$k]);
		}
		return $not_sign;
	}

	/**
	 * 根据某天和某月签到的日子获取某月未签到的日子
	 * @param array $days
	 * @param int $max_day
	 * @return array
	 */
	public function getNotSignByDays($days, $max_day) {
		$not_days = array();
		for ($k = 1; $k < $max_day; $k++) {
			if (in_array($k, $days)) continue;
			array_push($not_days, $k);
		}
		return $not_days;
	}

	/**
	 * 获取机器人API
	 * @return array | boolean
	 */
	public function getMe($uin, $group_member_id) {
		$sign = $this->db->executeQuery("SELECT * FROM web_plugin_sign WHERE uin = '{$uin}' AND group_member_id = {$group_member_id} ORDER BY id ASC LIMIT 1", true);
		if (!$sign) {
			$this->insertSign($uin, $group_member_id);
			$sign = $this->db->executeQuery("SELECT * FROM web_plugin_sign WHERE uin = '{$uin}' AND group_member_id = {$group_member_id} ORDER BY id ASC LIMIT 1", true);
		}
		return $sign;
	}

	/**
	 * 更新插件的运行状态
	 * @param string $status
	 * @return boolean
	 */
	public function updateStatus($uin, $group_member_id, $status = "") {
		return $this->db->executeQuery("UPDATE web_plugin_sign SET status = '{$status}' WHERE uin = '{$uin}' AND group_member_id = {$group_member_id}") > 0 ? true : false;
	}

	/**
	 * 增加群成员签到信息
	 * @param string $uin
	 * @param int $group_member_id
	 * @return int
	 */
	public function insertSign($uin, $group_member_id) {
		return $this->db->executeQuery("INSERT INTO web_plugin_sign(uin, group_member_id, createdate) VALUES('{$uin}', {$group_member_id}, ". time() . ")");
	}

	/**
	 * 修改签到信息
	 * @param string $uin
	 * @param int $group_member_id
	 * @param int $continuous_sign
	 * @param int $total_sign
	 * @param string $last_sign_time
	 * @return int
	 */
	public function updateSign($uin, $group_member_id, $continuous_sign, $total_sign, $last_sign_time) {
		return $this->db->executeQuery("UPDATE web_plugin_sign SET continuous_sign = {$continuous_sign}, total_sign = {$total_sign}, last_sign_time = '{$last_sign_time}' WHERE uin = '{$uin}' AND  group_member_id = {$group_member_id}");
	}

	/**
	 * 获取某年某月已经签到的日子
	 * @param int $sign_id
	 * @param int $year
	 * @param int $month
	 * @return array
	 */
	public function getRecordByDate($sign_id, $year, $month) {
		$record = $this->db->executeQuery("SELECT days FROM web_plugin_sign_record WHERE sign_id = {$sign_id} AND year = {$year} AND month = {$month}", true);
		$dayArray = array();
		if ($record) {
			$days = explode(",", $record['days']);
			for ($i = 0; $i < count($days); $i++) {
				if ($days[$i] == "") continue;
				array_push($dayArray, intval($days[$i]));
			}
		}
		return $dayArray;
	}

	/**
	 * 按照某月没有签到的日子补签
	 * @param int $sign_id
	 * @param int $year
	 * @param int $month
	 * @param string $sign_days
	 * @return boolean
	 */
	public function addSignRecord($sign_id, $year, $month, $sign_days) {
		return $this->db->executeQuery("REPLACE INTO web_plugin_sign_record(sign_id, year, month, days) VALUES({$sign_id}, '{$year}', '{$month}', '{$sign_days}')") > 0 ? true : false;
	}

}
?>